from fastapi import HTTPException
import httpx

from core.Log import log_admin_event
from core.Config import settings
from models.admin.system.Sms import EnvetEnum, sys_sms

class SmsServer:
    def __init__(self) -> None:
        pass

    @staticmethod
    async def send_sms(mobile: str,code: str, event: EnvetEnum):
        if settings.SMS["type"] == "jhsh":
            tpl_id = settings.SMS[event.value+"templateCode"]
            if not tpl_id:
                raise HTTPException(status_code=400, detail='sms tep_id not found')
            params = {
                'key': settings.SMS["accessKeyId"],
                'mobile': mobile,  # 接收短信的用户手机号码
                'tpl_id': tpl_id,  # 短信模板ID
                'tpl_value': f'#code#={code}&#m#=3'  # 模板变量
            }
            try:
                async with httpx.AsyncClient() as client:
                    response = await client.get(url= settings.SMS["apiUrl"], params=params)
                    response.raise_for_status()
                    resulte = response.json()
                    # {'reason': '错误的短信模板ID,请通过后台确认!!', 'result': None, 'error_code': 205402}
                    # {'reason': '操作成功', 'result': {'sid': 'A1577706A33A87BC', 'fee': 1, 'count': 1}, 'error_code': 0}
                    # 判断 error_code 是否为0
                    if resulte["error_code"] == 0:
                        return True
                    else:
                        return False
            except httpx.RequestError as e:
                log_admin_event(f"SMS SEND Request error: {e} ")
                raise HTTPException(status_code=400, detail=f"Request error: {e}")
            except httpx.HTTPStatusError as e:
                log_admin_event(f"SMS SEND HTTP error: {e} ")
                raise HTTPException(status_code=e.response.status_code, detail=f"HTTP error: {e}")
        elif settings.SMS.type == "aliyun":
            pass
